#include "reader.h"

Reader::Reader(Shell *shell, int timeout, QObject *parent)
    : QObject(parent)
    , QRunnable()
    , m_shell(shell)
    , m_timeout(timeout)
{}

void Reader::run()
{
    while (true)
    {
        bool read = false;
        int pos = 0;
        while (!read)
        {
            int shell_size = m_shell->size();
            if (shell_size)
            {
                pos = qrand() % shell_size;
                read = m_shell->try_asquire_for_read(pos);
            }
        }
        emit i_m_reading();
        ::sleep(m_timeout);
        m_shell->release_book(pos);
        emit i_m_waiting();
    }
}

void Reader::set_timeout(int timeout)
{
    m_timeout = timeout;
}
